/**
 * @format
 */

import React from 'react';
import {
  AppRegistry,
  Text,
  TextInput,
  Platform,
  StyleSheet
} from 'react-native';
import App from './src/App';
import { name as appName } from './app.json';

if (__DEV__) {
  // TODO 更好的做法是打包时注入调试选项
  const { connectToDevTools } = require('react-devtools-core');
  connectToDevTools();
} else {
  console.log = () => {};
}

console.disableYellowBox = true;

const styles = StyleSheet.create({
  defaultFontFamily: {
    fontFamily: ''
  }
});

// 解决rn字体随系统字体变化，参考: https://juejin.im/post/5ce66c26e51d4555fd20a2a0
const TextRender = Text.render;

const settings = [
  {
    fontFamily: 'sans-serif-thin',
    fontWeight: 'normal'
  },
  {
    fontFamily: 'sans-serif-light',
    fontWeight: 'normal'
  },
  {
    fontWeight: 'normal'
  },
  {
    fontFamily: 'sans-serif',
    fontWeight: 'bold'
  },
  {
    fontFamily: 'sans-serif-medium'
  },
  {
    fontFamily: 'sans-serif-black',
    fontWeight: 'normal'
  }
];

const defaultIndex = 2;

if (Platform.OS === 'android') {
  Text.render = (...args) => {
    const originText = TextRender.apply(this, args);
    let useIndex = defaultIndex;

    if (originText.props.style) {
      const originStyle =
        originText.props.style instanceof Array
          ? originText.props.style
          : [originText.props.style];

      const resStyle = originStyle.reduce(
        (left, right) => ({ ...left, ...right }),
        {}
      );

      if (typeof resStyle.fontWeight !== 'undefined') {
        const { fontWeight } = resStyle;

        if (fontWeight === '100' || fontWeight === '200') {
          useIndex = 0;
        } else if (fontWeight === '300') {
          useIndex = 1;
        } else if (fontWeight === '400' || fontWeight === 'normal') {
          useIndex = 2;
        } else if (fontWeight === '500' || fontWeight === '600') {
          useIndex = 3;
        } else if (fontWeight === '700' || fontWeight === 'bold') {
          useIndex = 4;
        } else if (fontWeight === '800' || fontWeight === '900') {
          useIndex = 5;
        }
      }

      return React.cloneElement(originText, {
        allowFontScaling: false,
        style: [
          settings[defaultIndex],
          styles.defaultFontFamily,
          resStyle,
          settings[useIndex]
        ]
      });
    }

    return React.cloneElement(originText, {
      allowFontScaling: false,
      style: [originText.props.style, styles.defaultFontFamily]
    });
  };
} else {
  Text.render = (...args) => {
    const originText = TextRender.apply(this, args);
    return React.cloneElement(originText, {
      allowFontScaling: false
    });
  };
}

const TextInputRender = TextInput.render;
TextInput.render = (...args) => {
  const originText = TextInputRender.apply(this, args);
  return React.cloneElement(originText, {
    allowFontScaling: false
  });
};

AppRegistry.registerComponent(appName, () => App);
